package com.study.spmongodb.wwj.thread2.char04;

import java.util.List;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/7 20:25
 */
public class ThreadLifeCycleObserver implements LifeCycleListener {

    public static final Object LOCK = new Object();

    public void concurrentQuery(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        ids.stream().forEach(id -> new Thread(new ObservableRunnable(this) {
            @Override
            public void run() {
                try {
                    notifyChange(new RunnableEvent(RunnableState.RUNNING, Thread.currentThread(), null));
                    System.out.println("query for the id " + id);
                    Thread.sleep(1000L);
                    notifyChange(new RunnableEvent(RunnableState.DONE, Thread.currentThread(), null));
                } catch (Exception e) {
                    notifyChange(new RunnableEvent(RunnableState.DONE, Thread.currentThread(), e));

                }
            }
        }).start());
    }

    @Override
    public void onEvent(ObservableRunnable.RunnableEvent event) {
        synchronized (LOCK) {
            System.out.println("the runnable [" + event.getThread().getName()
                    + " ] data change and state is [" + event.getState() + " ]"
            );
            if (event.getCasue() != null) {
                System.out.println("runnable [" + event.getThread().getName() + "] fail");
                event.getCasue().printStackTrace();
            }
        }
    }
}
